<?php

namespace app\zyhsapi\model;

use app\common\cachemodel\ZlcrAstr;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsConsultChatRtcRecordNow extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_consult_chat_rtc_record_now';

    protected $cacheModel = 'voice_consult.chat_rtc';

    /**
     * 保存当前连麦信息
     * @param int $type 1 =>用户   2=>占星师
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $id
     * @param array $data
     * @param int $chatDetailId
     * @param bool $isUpdate
     * @throws \Exception
     */
    public function saveNowRtcDataToCacheAndDB(int $type, int $appType, int $id, array $data, int $chatDetailId, bool $isUpdate = false)
    {
        if ($type === 2)
        {   // 占星师 的时候 写入数据库
            if ($isUpdate)
            {   // 更新
                $updateData = [];
                if (isset($data['status']))
                {
                    $updateData['status'] = $data['status'];
                }
                if (isset($data['id']))
                {
                    $updateData['rtc_id'] = $data['id'];
                }
                if (isset($data['recode_datas']))
                {
                    $updateData['recode_datas'] = $data['recode_datas'];
                }
                if (isset($data['dice_datas']))
                {
                    $updateData['dice_datas'] = $data['dice_datas'];
                }
                if (isset($data['tarot_datas']))
                {
                    $updateData['tarot_datas'] = $data['tarot_datas'];
                }
                if (isset($data['user_rtc_online']))
                {
                    $updateData['user_rtc_online'] = $data['user_rtc_online'];
                }
                if (isset($data['astr_rtc_online']))
                {
                    $updateData['astr_rtc_online'] = $data['astr_rtc_online'];
                }
                if (isset($data['gift_id']))
                {
                    $updateData['gift_id'] = $data['gift_id'];
                }
                if ($updateData)
                {
                    $this->where(['chat_detail_id' => $chatDetailId])->update($updateData);
                }
            } else
            {   // 新增
                $insertData = [
                    'uid' => $data['uid'],
                    'app_type' => $appType,
                    'astr_id' => $id,
                    'rtc_id' => $data['id'],
                    'rtc_sign' => $data['rtc_sign'],
                    'chat_detail_id' => $data['chat_id'],
                    'request_time' => $data['request_time'],
                    'status' => $data['status'],
                    'recode_datas' => $data['recode_datas'] ?? '',
                    'dice_datas' => $data['dice_datas'] ?? '',
                    'tarot_datas' => $data['tarot_datas'] ?? '',
                    'gift_id' => $data['gift_id'] ?? 0,
                ];
                // 入库
                $this->insert($insertData);
            }
        }
        if ($type === 1)
        {   // 用户key
            $cacheId = "user:{$appType}:{$id}";
        } else
        {
            $cacheId = 'astro:' . $id;
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('now_rtc', $cacheId)->setCache($data, 'now_rtc', $isUpdate);
    }

    /**
     * 获取当前 连麦信息
     * @param int $type 1=>用户   2=>占星师
     * @param int $appType
     * @param int $id
     * @param array $filed
     * @return array
     * @throws \Exception
     */
    public function getNowRtcDataByCache(int $type, int $appType, int $id, array $filed = [])
    {
        if ($type === 1)
        {   // 用户key
            $cacheId = "user:{$appType}:{$id}";
        } else
        {
            $cacheId = 'astro:' . $id;
        }
        return CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('now_rtc', $cacheId)->getDataAndSet(function () use ($type, $appType, $id)
        {
            try
            {
                $time = time();
                if ($type === 1)
                {   // 用户
                    $where = ['app_type' => $appType, 'uid' => $id];
                    $field = 'rtc_id,rtc_sign,app_type,astr_id,status,request_time,chat_detail_id,gift_id';
                } else
                {   // 占星师
                    $where = ['astr_id' => $id];
                    $field = 'rtc_id,rtc_sign,app_type,uid,status,request_time,chat_detail_id,recode_datas,tarot_datas,dice_datas,user_rtc_online,astr_rtc_online,gift_id';
                }
                // 2天内的  连线数据
                $where['request_time'] = ['>', $time - 172800];
                $data = $this->where($where)->order('chat_detail_id desc')->field($field)->findOrFail()->toArray();

                if ((int)$data['status'] === 4)
                {
                    $data = [];
                }

                $resData = [];
                if ($data['status'] < 4)
                {
                    if ($type === 1)
                    {   // 用户 存储信息
                        $astrInfo = (new ZlcrAstr())->getInfoById($data['astr_id'], ['avatar', 'nickname']);

                        $resData = [
                            'id' => $data['rtc_id'],
                            'rtc_sign' => $data['rtc_sign'],
                            'app_type' => $data['app_type'],
                            'astr_id' => $data['astr_id'],    // 占星师ID
                            'nickname' => $astrInfo['nickname'],   // 占星师昵称
                            'avatar' => $astrInfo['avatar'],     // 占星师头像
                            'status' => $data['status'],     // 状态
                            'request_time' => $data['request_time'],   // 申请连线时间
                            'chat_id' => $data['chat_detail_id'],    // chat_detail_id
                            'gift_id' => $data['gift_id'],
                        ];
                    } else
                    {   // 占星师 存储信息
                        $userInfo = (new ZyhsUser())->getInfoById($data['uid'], ['nickname', 'avatar', 'uen']);

                        $resData = [
                            'id' => $data['rtc_id'],
                            'rtc_sign' => $data['rtc_sign'],
                            'app_type' => $data['app_type'],
                            'uid' => $data['uid'],
                            'nickname' => $userInfo['nickname'],
                            'avatar' => $userInfo['avatar'],
                            'uen' => $userInfo['uen'],  // 用户准了号
                            'status' => $data['status'],    // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中 4=>已挂断
                            'request_time' => $data['request_time'],    // 申请连线时间
                            'chat_id' => $data['chat_detail_id'],   // chat_detail_id
                            'recode_datas' => $data['recode_datas'],    // 档案信息
                            'tarot_datas' => $data['tarot_datas'],     // 塔罗信息
                            'dice_datas' => $data['dice_datas'],      // 骰子信息
                            'user_rtc_online' => $data['user_rtc_online'], // 用户是否在线 1=>在线 0=>不在线
                            'astr_rtc_online' => $data['astr_rtc_online'], // 占星师是否在线 1=>在线 0=>不在线
                            'gift_id' => $data['gift_id'],
                        ];
                    }

                    if ($type === 1)
                    {   // 用户key
                        $cacheId = "user:{$appType}:{$id}";
                    } else
                    {
                        $cacheId = 'astro:' . $id;
                    }
                    CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('now_rtc', $cacheId);
                }

                return $resData;
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, $filed, 'now_rtc');
    }

    /**
     * 删除当前连麦缓存
     * @param int $type 1=>用户   2=>占星师
     * @param int $appType 1=>准有好事 2=>准了APP
     * @param int $id
     * @param int $chatDetailId
     * @return void
     * @throws \Exception
     */
    public function delNowRtcDataByCacheAndDB(int $type, int $appType, int $id, int $chatDetailId)
    {
        if ($type === 1)
        {   // 用户key
            $cacheId = "user:{$appType}:{$id}";
        } else
        {
            $cacheId = 'astro:' . $id;
        }
        if ($type === 2)
        {   // 占星师 情况 更新至数据库
            $this->where(['chat_detail_id' => $chatDetailId])->update(['status' => 4, 'end_time' => time()]);
        }
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('now_rtc', $cacheId)->rmCache('now_rtc');
    }
}